package org.ktpro.shortlink.admin.common.biz.user;

import cn.hutool.core.util.StrUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 用户信息传输拦截器
 */
@RequiredArgsConstructor
@Slf4j
public class RequestHeaderContextInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 跳过健康检查请求
        if ("Consul Health Check".equals(request.getHeader("user-agent"))) {
            log.debug("Skipping health check request.");
            return true;
        }

        String username = request.getHeader("username");
        log.info("Received username: {}", username);

        if (StrUtil.isNotBlank(username)) {
            String userId = request.getHeader("userId");
            String realName = request.getHeader("realName");
            UserInfoDTO userInfoDTO = new UserInfoDTO(userId, username, realName);
            UserContext.setUser(userInfoDTO);
            log.debug("UserContext set with username: {}", username);
        } else {
            log.error("[ERROR] 请求中未包含用户名！");
        }

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContext.removeUser();
        log.debug("UserContext removed");
    }
}
